package com.mfz.common.servlet

import com.alibaba.fastjson.JSONObject
import com.mfz.common.definition.organization.User
import com.mfz.common.dbHelper.Helper
import com.mfz.common.encryption.Encryption
import com.mfz.common.servlet.BaseServlet.Companion.log
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 保存一个请求的上下文信息
 *init
 * create by 2019-06-19.
 * @author yimin
 */
class HttpContext(
	val requestType: HttpRequestType,
	val requestData: JSONObject,
	/**
		 * 这个user是在请求线程启动时候初始化的。对于这个对象的修改要注意可能覆盖其他人的修改
		 */
		var user: User?,
	/**
		 * 此值表明当前请求过来时是否进行过了加密操作
		 * 并且指明加密的方式
		 */
		val encryption: Encryption,
	val request:HttpServletRequest,
	val response: HttpServletResponse
) : AutoCloseable {
	val dbHelper: Helper = com.mfz.common.dbHelper.dbHelper
	var result: HttpResult = Success.it
	private var processVariable: HashMap<String, Any>? = null

	init {
	}

	/**
	 * 此方法为此次执行结束后需要进行退出时被调用。
	 *
	 * 所有在此对象当中被使用的需要释放的均在此进行统一的处理
	 * 此方法执行一些清理动作。
	 */
	override fun close() {
		log.trace("线程：${Thread.currentThread().name}，退出前关闭操作。")
		//如果向前台返回异常，所有操作进行回滚
		dbHelper.close(needSaveData = true, closeThread = true, commit = result is Success)
	}

	operator fun get(name: String): Any? {
		return if (processVariable == null) null
		else
			(processVariable as HashMap)[name]
	}

	operator fun set(name: String, value: Any) {
		if (processVariable == null) processVariable = HashMap()

		(processVariable as HashMap)[name] = value
	}
}
